<template>
  <div class="tabs-container">
    <el-form size="small" :inline="true">
      <el-form-item>
        <el-input v-model="title" placeholder="请输入标签标题"></el-input>
      </el-form-item>
      <el-form-item>
        <el-input v-model="content" placeholder="请输入标签内容"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="open('add')" icon="el-icon-plus"
          >新增标签</el-button
        >
        <el-button icon="el-icon-search" @click="getList" type="primary"
          >查询标签</el-button
        >
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column prop="title" label="标签标题" />
      <el-table-column prop="content" show-overflow-tooltip label="标签内容">
        <template slot-scope="scope">
          <el-button type="text" @click="previewClick(scope.row)" size="small"
            >预览</el-button
          >
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="上传时间">
        <template slot-scope="scope">
          {{ formatDate(1, scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间">
        <template slot-scope="scope">
          {{ formatDate(1, scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="address" align="center" label="操作" width="140">
        <template slot-scope="scope">
          <el-button
            type="text"
            style="margin-right: 0.6rem"
            @click="editClick(scope.row)"
            size="small"
            >编辑</el-button
          >
          <el-popconfirm
            @onConfirm="deleteClick(scope.row.id)"
            title="确定删除该标签吗？"
          >
            <template #reference>
              <el-button style="color: red" type="text" size="small"
                >删除</el-button
              >
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      @close="close"
      title="新增标签"
      :visible.sync="dialogVisible"
      width="50%"
    >
      <span>
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="标签标题" prop="title">
            <el-input
              maxlength="6"
              show-word-limit
              placeholder="请输入标签标题"
              v-model="form.title"
              clearable
              ref="noticeInput"
            ></el-input>
          </el-form-item>
          <el-form-item prop="content">
            <div style="color: #606266; font-size: 14px; font-weight: bold">
              <span style="color: #f56c6c">* </span>标签内容
            </div>
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editor"
                :defaultConfig="toolbarConfig"
                mode="default"
              />
              <Editor
                style="height: 300px; overflow-y: hidden"
                v-model="html"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="onCreated"
              />
            </div>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button
          @click="dialogVisible = false"
          v-if="openType === 'add' || openType === 'edit'"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="onSubmit"
          :loading="btnLoading"
          v-if="openType === 'add' || openType === 'edit'"
          >确 定</el-button
        >
        <el-button
          type="primary"
          @click="dialogVisible = false"
          v-if="openType === 'preview'"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { list, upload, del, update } from "@/api/tabs";
import { uploadFile } from "@/api";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
export default {
  name: "tabs",
  components: { Editor, Toolbar },
  data() {
    return {
      title: "",
      content: "",
      tableData: [],
      loading: false,
      dialogVisible: false,
      btnLoading: false,
      openType: "add",

      editor: null,
      toolbarConfig: {},
      editorConfig: {
        MENU_CONF: {
          uploadImage: {
            async customUpload(file, insertFn) {
              const formData = new FormData();
              formData.append("file", file);
              const res = await uploadFile(formData);
              if (res.code === 200) {
                insertFn(res.data);
              }
            },
          },
          fontSize: {
            fontSizeList: [
              "12px",
              "14px",
              "16px",
              "18px",
              "20px",
              "22px",
              "24px",
              "26px",
              "28px",
              "30px",
              "32px",
            ],
          },
        },
      },
      html: "",
      form: {
        title: "",
        content: "",
        id: null,
      },
      rules: {
        title: [
          { required: true, message: "请输入标签标题", trigger: "blur" },
          { max: 6, message: "标题最多6个字符", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入标签内容", trigger: "blur" },
        ],
      },
    };
  },
  // 组件销毁
  beforeDestroy() {
    this.editor && this.editor.destroy();
  },
  mounted() {
    this.getList();
  },
  watch: {
    dialogVisible(newVal) {
      newVal && (this.html = this.form.content);
    },
  },
  methods: {
    // 预览
    previewClick(row) {
      const { title, content } = row;
      this.form = { title, content };
      this.open("preview");
    },
    // 创建编辑器
    onCreated(editor) {
      this.editor = Object.seal(editor); // 一定要用 Object.seal()，否则会报错
      console.log(this.editor.children);
    },

    // 重置表单
    resetForm() {
      this.form = {
        title: "",
        content: "",
        id: null,
      };
      this.$refs.form && this.$refs.form.resetFields();
    },

    // 编辑
    editClick(row) {
      const { title, content, id } = row;
      this.form = { title, content, id };
      this.open("edit");
    },

    // 打开弹窗
    open(type) {
      this.openType = type;
      this.$nextTick(() => {
        this.$refs.noticeInput.focus();
      });
      this.dialogVisible = true;
    },

    // 关闭弹窗
    close() {
      this.resetForm();
    },

    // 提交
    async onSubmit() {
      try {
        const valid = await this.$refs.form.validate();
        if (!valid) return;

        this.btnLoading = true;
        const request = this.form.id ? update : upload;
        this.form.content = this.html;
        const res = await request(this.form);

        if (res.code === 200) {
          this.$message.success(res.message);
          this.dialogVisible = false;
          this.getList();
        }
      } catch (error) {
        this.$message.error("操作失败，请重试");
      } finally {
        this.btnLoading = false;
      }
    },

    // 查询
    async getList() {
      try {
        this.loading = true;
        const res = await list();
        if (res.code === 200) {
          this.tableData = res.data;
        }
      } catch (error) {
        this.$message.error("获取数据失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 删除
    async deleteClick(id) {
      try {
        const res = await del(id);
        if (res.code === 200) {
          this.$message.success(res.message);
          this.getList();
        }
      } catch (error) {
        this.$message.error("删除失败，请重试");
      }
    },
  },
};
</script>

<style src="@wangeditor/editor/dist/css/style.css"></style>
